import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import * as fromRoot from '../../reducers';
import * as quoteActions from '../../actions/quote.action';
import { Quote } from '../../domain/index';
import { Store } from '@ngrx/store';
import { LoadAction } from '../../actions/quote.action';
import { LoginAction } from '../../actions/auth.action';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  quote$: Observable<Quote>;
  constructor(private fb: FormBuilder,
    private store$: Store<fromRoot.State>
  ) {
    this.quote$ = this.store$.select(fromRoot.getQuote);
    this.store$.dispatch(new LoadAction(null));
  }

  ngOnInit() {
    // 使用默认的formGroup
    // this.loginForm = new FormGroup({
    //   email: new FormControl('wang@163.com', Validators.compose([Validators.required, Validators.email])),
    //   password: new FormControl('', Validators.required),
    // });

    // 使用formBuilder
    this.loginForm = this.fb.group({
      email: ['wpcfan@163.com', [Validators.required, Validators.email]],
      password: ['wp123456', Validators.required],
    });
  }
  onSubmit({ value, valid }, ev: Event) {
    ev.preventDefault(); // 阻止默认行为 防止刷新页面
    if (!valid) {
      return;
    }
    this.store$.dispatch(new LoginAction(value));
  }
}
